#include "tserialport.h"

TserialPort::TserialPort(QObject *parent)
    : QObject{parent}
{
    comPort = new QSerialPort;
    comPort->setReadBufferSize(102400);
    // thread = new QThread(this);
    // this->moveToThread(thread);
    // thread->start();
    // qDebug()<<this<<thread->currentThread();
    //长时间挂测，这个槽信号可能会断开
    connect(comPort,SIGNAL(readyRead()),this,SLOT(on_serialPort_ready()));
    connect(comPort,SIGNAL(errorOccurred(QSerialPort::SerialPortError)),this,SLOT(on_errorOccurred(QSerialPort::SerialPortError)));
}

TserialPort::~TserialPort()
{
    if(thread)
    {
        thread->requestInterruption();
        thread->quit();
        thread->wait();
    }
}

void TserialPort::openPort(QString name, QSerialPort::BaudRate baudRate, QSerialPort::DataBits dataBits, QSerialPort::Parity parity, QSerialPort::StopBits stopBits)
{
    portName = name;
    comPort->setPortName(name);
    comPort->setBaudRate(baudRate);
    comPort->setDataBits(dataBits);
    comPort->setParity(parity);
    comPort->setStopBits(stopBits);
    if(comPort->open(QIODevice::ReadWrite))
    {
        emit serialStateChanged(1, portName,"open success");
    }
    else
    {
        emit serialStateChanged(0, portName,"open fail");
    }
}

void TserialPort::closePort()
{
    comPort->close();
    emit serialStateChanged(0, portName,"close success");
}

void TserialPort::writeData(QByteArray data)
{
    comPort->write(data);
    // comPort->waitForBytesWritten();
}

void TserialPort::on_serialPort_ready()
{
    if(comPort->bytesAvailable())
    {
        emit serialRevReport(comPort->readAll());
    }
}

void TserialPort::on_errorOccurred(QSerialPort::SerialPortError error)
{
    if(error == QSerialPort::NoError || error == QSerialPort::TimeoutError)
    {
        return;
    }
    qDebug()<<portName<<" error="<<error;
    if(comPort->isOpen())
    {
        comPort->close();
    }
    emit serialStateChanged(2, portName,"error="+error);
}
